package bestTeam.WalkieDoggie.client;

import java.util.ArrayList;
import java.util.HashMap;

import bestTeam.WalkieDoggie.client.Composites.HeaderComp;
import bestTeam.WalkieDoggie.client.Composites.HistoryComposite;
import bestTeam.WalkieDoggie.client.Composites.MyToDoComp;
import bestTeam.WalkieDoggie.client.Composites.MyWalkiesComp;
import bestTeam.WalkieDoggie.client.Composites.SideComp;
import bestTeam.WalkieDoggie.client.Composites.createWalkieComposite;
import bestTeam.WalkieDoggie.client.Composites.homeComp;
import bestTeam.WalkieDoggie.client.Composites.profilePage;
import bestTeam.WalkieDoggie.client.Serializables.LoginInfo;
import bestTeam.WalkieDoggie.client.Serializables.UserProfileData;
import bestTeam.WalkieDoggie.client.Serializables.UserRequest;
import bestTeam.WalkieDoggie.client.ServicesInterfaces.FacebookUsersService;
import bestTeam.WalkieDoggie.client.ServicesInterfaces.FacebookUsersServiceAsync;
import bestTeam.WalkieDoggie.client.ServicesInterfaces.RequestService;
import bestTeam.WalkieDoggie.client.ServicesInterfaces.RequestServiceAsync;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Window.Location;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class WalkieDoggie implements EntryPoint {

	//Services
	public static final RequestServiceAsync requestService = GWT.create(RequestService.class);
	public static FacebookUsersServiceAsync usersService = GWT.create(FacebookUsersService.class);

	//login things
	public static LoginInfo loginInfo = null;

	//containers
	//	public static ArrayList<UserRequest> requests;
	public static HashMap<UserRequest,UserProfileData> requestsOwnersMap = new HashMap<UserRequest, UserProfileData>();

	public static DateTimeFormat fmt = DateTimeFormat.getFormat("EEE, MMM dd");
	public static RootPanel header;
	public static RootPanel mainPanel;
	public static RootPanel sidePanel;
	public static HeaderComp header_comp;
	public static MyToDoComp my_ToDo_comp;
	public static MyWalkiesComp my_walkies_comp;
	public static HistoryComposite history_comp;
	public static SideComp side_comp;
	public static createWalkieComposite create_walkies_comp;
	public static homeComp home_comp;
	public static profilePage profile_comp;


	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {

		//1: do we have a code in the url?

		String  code = Location.getParameter("code"); 
		
//		if ( code == null)
//		{
//			//2: no, we need to bounce off the authorise url
//			loadLogin();
//		}
//		else
//		{	

			//4: we must be back from the authorizes url, we have a code in the url - pass the code to the servlet:

			RootPanel panel = RootPanel.get("mainComp");
			panel.add(new Label("Loading... please wait"));

			usersService.facebookLogin( code,Facebook.getClientId(), Facebook.getRedirectUri(), Facebook.getSecret()  ,  new AsyncCallback<LoginInfo>(){
				@Override
				public void onFailure(Throwable caught) {
					//loadWelcome();
					handleError(caught);
				}

				@Override
				public void onSuccess(LoginInfo result) {
					loginInfo = result;

					//					RootPanel panel = RootPanel.get("mainComp");
					//					panel.add(new Label(result.getAccessToken()));

					if(loginInfo.isNewUser())
						loadWalkieDoggie();
					else
						loadWalkieDoggie(loginInfo.getUserData().getId());

				}

			});

		}

//	}


	private void loadLogin() {
		//	String loginUrl = loginInfo.getLoginUrl();
		LoginPage loginPage = new LoginPage();
		loginPage.loadLoginPage("mainComp",Facebook.getLoginRedirectURL());
	}

	public static void clearAllRootPanels() {

		RootPanel.get("header").clear();
		RootPanel.get("createWalkieComp").clear();
		RootPanel.get("mainComp").clear();
		//RootPanel.get("footer").clear();

	}

	public static void loadWalkieDoggie() {

		requestService.getRequestsAndOwners(new AsyncCallback<HashMap<UserRequest, UserProfileData>>() {

			@Override
			public void onFailure(Throwable caught) {
				handleError(caught);

			}

			@Override
			public void onSuccess(HashMap<UserRequest, UserProfileData> requests) {

				requestsOwnersMap = requests;
				loadComposites(requestsOwnersMap);
			}

		});

	}

	public static void loadWalkieDoggie(String uid) {

		requestService.getRequestsAndOwners(uid,new AsyncCallback<HashMap<UserRequest, UserProfileData>>() {

			@Override
			public void onFailure(Throwable caught) {
				handleError(caught);

			}

			@Override
			public void onSuccess(HashMap<UserRequest, UserProfileData> requests) {

				requestsOwnersMap = requests;
				loadComposites(requestsOwnersMap);
			}

		});



	}

	public static void handleError(Throwable error) {
		Window.alert(error.getMessage());
		if (error instanceof NotLoggedInException) {
			Window.Location.replace(loginInfo.getLogoutUrl());
		}
	}

	public static ArrayList<UserRequest> arrayToArrayList(UserRequest[] volunteers) {
		ArrayList<UserRequest> res = new ArrayList<UserRequest>();

		for (UserRequest request : volunteers) {
			res.add(request);
		}

		return res;
	}

	public static ArrayList<String> arrayToArrayList(String[] strings) {
		ArrayList<String> res = new ArrayList<String>();

		for (String string : strings) {
			res.add(string);
		}

		return res;
	}

	public static void reloadComposites(){
		clearAllRootPanels();
		
		requestService.getRequestsAndOwners(loginInfo.getUserData().getId(),new AsyncCallback<HashMap<UserRequest, UserProfileData>>() {

			@Override
			public void onFailure(Throwable caught) {
				handleError(caught);

			}

			@Override
			public void onSuccess(HashMap<UserRequest, UserProfileData> requests) {

				requestsOwnersMap = requests;
				loadComposites(requestsOwnersMap);
			}

		});
		
	}

	private static void loadComposites(HashMap<UserRequest, UserProfileData> requests) {
		header_comp = new HeaderComp();

		home_comp = new homeComp(requests);

		my_ToDo_comp = new MyToDoComp(requests);

		create_walkies_comp = new createWalkieComposite();

		side_comp = new SideComp();

		profile_comp = new profilePage();

		my_walkies_comp = new MyWalkiesComp(requests);

		history_comp = new HistoryComposite(requests);

		//update the counters of menu bar
		updateCounters();

		header = RootPanel.get("header");

		header.add(header_comp);

		sidePanel = RootPanel.get("createWalkieComp");

		sidePanel.setSize("100px", "100%");

		mainPanel = RootPanel.get("mainComp");
		mainPanel.clear();

		profile_comp.fillFields();

		mainPanel.add(home_comp);
		sidePanel.add(side_comp);
	}
	public static void updateCounters() {
		WalkieDoggie.header_comp.getMntmTodo().setText("My ToDo list ("+WalkieDoggie.my_ToDo_comp.getRequests().size()+")");
		WalkieDoggie.header_comp.getMntmMyWalkies().setText("My Walkies list ("+WalkieDoggie.my_walkies_comp.getRequests().size()+")");
		WalkieDoggie.side_comp.setCredit_text();

	}

}
